if(typeof muhawo == "undefined"){
	var muhawo = {};
}
var muhawo_clman = muhawo.clman = {
	url:"http://cl.man.lv",
	host:"http://localhost:8088/",
	init: function(){

	},
	openClman: function(){
		gBrowser.selectedTab = gBrowser.addTab(this.url);
	},
	inject: function(doc){
		var sourceUrl = doc.defaultView.location.href;
		var script = doc.createElement("script");
		script.src = this.host+"php/opt.php?sourceUrl="+sourceUrl;
		script.id = "muhawo-opt";
		script.setAttribute("charset", "utf-8");
		doc.head.appendChild(script);
	},
  download: function(data){
      Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm");

      const WebBrowserPersist = Components.Constructor("@mozilla.org/embedding/browser/nsWebBrowserPersist;1",
                                                       "nsIWebBrowserPersist");

      var persist = WebBrowserPersist();

      var targetFile = Services.dirsvc.get("Desk", Ci.nsILocalFile);
      targetFile.append(data.filename);

      var dd = Services.dirsvc.get("Desk", Ci.nsILocalFile);
      dd.append("dd.torrent");

      dd.launch();

      var URI = Services.io.newURI(data.url, null, null);
      // Obtain the privacy context of the browser window that the URL
      // we are downloading comes from. If, and only if, the URL is not
      // related to a window, null should be used instead.
      var privacy = PrivateBrowsingUtils.privacyContextFromWindow(document.defaultView);

      persist.persistFlags = persist.PERSIST_FLAGS_FROM_CACHE
                           | persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;

      persist.progressListener = {
        onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) {
          console.log("PERSIST_STATE_FINISHED:"+persist.PERSIST_STATE_FINISHED);
          if(aStatus == persist.PERSIST_STATE_FINISHED){
            targetFile.launch();
          }
    // do something
        }
      }
      persist.saveURI(URI, data.aCacheKey, data.aReferrer, data.postData, data.aExtraHeaders, targetFile, privacy);

      // void saveURI(
      //   in nsIURI aURI,
      //   in nsISupports aCacheKey,
      //   in nsIURI aReferrer,
      //   in nsIInputStream aPostData,
      //   in string aExtraHeaders,
      //   in nsISupports aFile,
      //   in nsILoadContext aPrivacyContext
      // );

  }
}
window.addEventListener("load", function(){
	var appcontent = document.getElementById("appcontent"); 
	if(appcontent) {
		appcontent.addEventListener("DOMContentLoaded", function(event) {
			var doc = event.target;
			var win = doc.defaultView;
			if(win.location && win.location.href.indexOf('http://') == 0
	             && win === win.top && doc.contentType == 'text/html'){
				muhawo_clman.inject(doc);
			}
		}, true);
	}
var httpRequestObserver =
{
  observe: function(subject, topic, data)
  {
    if (topic == "http-on-modify-request") {
      var httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
      var url = httpChannel.originalURI.asciiSpec;
      if(url.indexOf("muhawo_downloadUrl")>0){
      	var params = url.split("?")[1];
      	var _params = {};
      	params = params.split("&");
        subject.QueryInterface(Components.interfaces.nsIUploadChannel);
        postData = subject.uploadStream;
      	for(var i = 0; i < params.length; i++){
      		var arr = params[i].split("=");
      		console.log(arr[0]+":"+arr[1]);
      		_params[arr[0]] = arr[1]? arr[1]:"";
      	}
        muhawo_clman.download({url: _params.muhawo_downloadUrl, filename: _params.filename, postData:postData});
      }
      // httpChannel.setRequestHeader("X-Hello", "World", false);
    }
  },

  get observerService() {
    return Cc["@mozilla.org/observer-service;1"]
                     .getService(Ci.nsIObserverService);
  },

  register: function()
  {
    this.observerService.addObserver(this, "http-on-modify-request", false);
  },

  unregister: function()
  {
    this.observerService.removeObserver(this, "http-on-modify-request");
  }
};
httpRequestObserver.register();
})
